package com.xmy.studentmanager.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xmy.studentmanager.pojo.Grade;
import com.xmy.studentmanager.pojo.Student;
import com.xmy.studentmanager.service.GradeService;
import com.xmy.studentmanager.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * @Author: xmy
 * @Date: 2019-04-23 13:43
 * @Version 1.0
 */
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private GradeService gradeService;

    @GetMapping(value = {"/students/{pageNumber}","/students"})
    public String selAllStudent(@PathVariable(value = "pageNumber",required = false) Integer pageNumber,String name,Integer gradeId,Model model){
        if (pageNumber==null){
            pageNumber=1;
        }
        Integer pageSize = 4;
        PageHelper.startPage(pageNumber,pageSize);
        List<Student> students = studentService.selAllStudent(name,gradeId);
        PageInfo<Student> pageInfo = new PageInfo<Student>(students);
        List<Grade> grades = gradeService.selAllGrade();
        model.addAttribute("grades",grades);
        model.addAttribute("students",students);
        model.addAttribute("pageNumber",pageNumber);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("name",name);
        model.addAttribute("gradeId",gradeId);
        return "studentList";
    }

    @GetMapping("/delete/{id}")
    public String delStudent(@PathVariable("id") Integer id){
        studentService.delStudent(id);
        return "redirect:/students";
    }

    @GetMapping("/add")
    public String addStudent(Student student,Model model){
        studentService.addStudent(student);
        List<Grade> grades = gradeService.selAllGrade();
        model.addAttribute("grades",grades);
        return "redirect:/students";
    }

    @GetMapping("/modify")
    public String modifyStudent(Student student){
        studentService.updateStudent(student);
        return "redirect:/students";
    }

    @GetMapping("/selbyid/{id}")
    public String modifyStudent(@PathVariable("id") Integer id,Model model){
        Student student = studentService.selStudentById(id);
        List<Grade> grades = gradeService.selAllGrade();
        model.addAttribute("student",student);
        model.addAttribute("grades",grades);
        return "handle";
    }

    @GetMapping("/gotoadd")
    public String goToAdd(Model model){
        List<Grade> grades = gradeService.selAllGrade();
        model.addAttribute("grades",grades);
        return "handle";
    }
}
